package DesignPattern.Proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class Dynamic {
    public static void main(String[] args) {
        SourceObject sourceObject = new SourceObject();

        DynamicProxy dynamicProxy = new DynamicProxy(sourceObject);

        ProxyInterface proxy = (ProxyInterface) dynamicProxy.getProxy();
        proxy.sendMsg();
    }
}

class DynamicProxy implements InvocationHandler{

    private Object target;

    public DynamicProxy(Object target){
        super();
        this.target = target;
    }

    public DynamicProxy(){
        super();
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("start send msg");
        Object invoke = method.invoke(target, args);
        System.out.println("stop send msg");
        return invoke;
    }

    public Object getProxy(){
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), target.getClass().getInterfaces(), this);
    }
}
